﻿@{
    ViewBag.Title = "Datagrid全自定义配置的列信息，并包含编辑器配置信息和常规的CUD功能";
}
<link href="~/Scripts/jquery-plugins/My97DatePicker/skin/WdatePicker.css" rel="stylesheet" />
<script src="~/Scripts/jquery-plugins/My97DatePicker/WdatePicker.js"></script>
<link href="~/Scripts/jquery-easyui-extensions/validatebox/jeasyui.extensions.validatebox.css" rel="stylesheet" />
<script src="~/Scripts/jquery-easyui-extensions/validatebox/jeasyui.extensions.validatebox.rules.js"></script>
<link href="~/Scripts/jquery-easyui-extensions/datagrid/jeasyui.extensions.datagrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-easyui-extensions/menu/jeasyui.extensions.menu.js"></script>
<script src="~/Scripts/jquery-easyui-extensions/datagrid/jeasyui.extensions.datagrid.columnToggle.js"></script>
<script src="~/Scripts/jquery-easyui-extensions/datagrid/jeasyui.extensions.datagrid.findRow.js"></script>
<script src="~/Scripts/jquery-easyui-extensions/datagrid/jeasyui.extensions.datagrid.moreEditors.js"></script>



<div class="easyui-layout" data-options="fit:true">
    <div data-options="region:'north',border:false,title:'预留'" style="height:180px;border-bottom-width:1px;">
        <div id="groupedFieldInfo" style="padding:8px;"></div>
        <span id="opSpan" style="color:red;"></span>
    </div>
    <div data-options="region:'center',border:false,title:'测试Datagrid'">
        <table id="dg"></table>
    </div>
</div>


<script>
    var inserts = [], updates = [], deletes = [];


    function attachRowToCache(row, isDeleted) {
        var opts = $("#dg").datagrid("options"), idField = opts.idField, id = row[idField], isNew = $.string.contains(id, "-");
        if (isDeleted) {
            //deletes.push($.array.clone(row));
        } else {
            if (isNew) {
                //新增保存后，更新id，去掉-
                row[idField] = $.string.replaceAll(id, "-", "");
                //inserts.push(row);
            } else {
                //

            }
        }
        $("#opSpan").append((isDeleted ? "删除" : isNew ? "新增" : "修改") + "了数据：" + JSON.stringify(row)).append("<br /><br />");
    }

    function endEdit(thisArg, e, id) {
        var row = $("#dg").datagrid("findRow", id);
        if (!row) {
            row = $("#dg").datagrid("findRow", $.string.replaceAll(id, "-", ""));
        }
        if (row) {
            var rowIndex = $("#dg").datagrid("getRowIndex", row);
            $("#dg").datagrid("endEdit", rowIndex);
            e.stopPropagation();
        }
    }

    function beginEdit(thisArg, e, id) {
        var row = $("#dg").datagrid("findRow", id);
        if (!row) {
            row = $("#dg").datagrid("findRow", $.string.replaceAll(id, "-", ""));
        }
        if (row) {
            var rowIndex = $("#dg").datagrid("getRowIndex", row);
            $("#dg").datagrid("beginEdit", rowIndex);
            //把开启编辑按钮替换成结束编辑 需要替换是因为开启编辑时执行操作列的formatter
            $(thisArg).text("结束编辑")
                .removeClass("datagrid_btn_beginEdit").addClass("datagrid_btn_endEdit")
                .removeAttr("onclick").click(function (e) {
                    endEdit(this, e, id);
                });
            e.stopPropagation();
        }
    }

    function trySave(thisArg, e, id) {
        var row = $("#dg").datagrid("findRow", id);
        if (!row) {
            row = $("#dg").datagrid("findRow", $.string.replaceAll(id, "-", ""));
        }
        if (row) {
            if (row.isEditing) {
                //正在编辑，尝试结束编辑
                var rowIndex = $("#dg").datagrid("getRowIndex", row);
                $("#dg").datagrid("endEdit", rowIndex);
            }
            if (!row.isEditing) {
                attachRowToCache(row, false);
            }
            e.stopPropagation();
        }
    }

    function tryRemove(thisArg, e, id) {
        var row = $("#dg").datagrid("findRow", id);
        if (!row) {
            row = $("#dg").datagrid("findRow", $.string.replaceAll(id, "-", ""));
        }
        if (row) {
            attachRowToCache(row, true);
            var rowIndex = $("#dg").datagrid("getRowIndex", row);
            $("#dg").datagrid("deleteRow", rowIndex);
            e.stopPropagation();
        }
    }

    $(function () {

        var targetDg = $("#dg"),
            insertPosition = "bottom",
            defaultRow = { isEditing: false }, // 在获取自定义列配置之后，为默认row赋值数据结构
            showDefaultCols = false, // 是否显示默认列
            showOperateCols = true, // 是否显示操作列
            columnComboboxUrl = "/Demo/GetCustomizeComboboxData?type=", // 列编辑器中下拉框数据源的请求url
            editors = $.fn.datagrid.defaults.editors;

        // 获取新增数据行的目标位置索引
        var getInsertRowIndex = function () {
            return insertPosition == "top" ? 0 : targetDg.datagrid("getRows").length;
        }

        // 获取列信息
        var getColumns = function (dgInit) {

            $.post("/Demo/GetCustomizeColumnsConfigData", {}, function (result) {

                var cols = [];
                var defaults = [{
                    field: 'Matrixkey', title: '默认列（当不存在自定义列时显示）', width: 180,
                    gatherable: true, hidable: false,
                    editor: {
                        type: "validatebox",
                        options: {
                            required: true
                        }
                    }
                }];

                var operates = [
                    {
                        field: "op", title: "操作", width: 120,
                        hidable: false,
                        formatter: function (val, row, rowIndex) {
                            var strHtml = "";
                            if (row.isEditing) {
                                strHtml += "<a class=\"datagrid_btn_endEdit\" href=\"javascript:void(0);\" onclick=\"endEdit(this, event,'" + row.ID + "')\">结束编辑</a>";
                            } else {
                                strHtml += "<a class=\"datagrid_btn_beginEdit\" href=\"javascript:void(0);\" onclick=\"beginEdit(this, event,'" + row.ID + "')\">开启编辑</a>";
                            }
                            //保存按钮
                            strHtml += "&nbsp;&nbsp;<a class=\"datagrid_btn_save\" href=\"javascript:void(0);\" onclick=\"trySave(this, event,'" + row.ID + "')\">保存</a>";
                            //删除按钮
                            strHtml += "&nbsp;&nbsp;<a class=\"datagrid_btn_remove\" href=\"javascript:void(0);\" onclick=\"tryRemove(this, event,'" + row.ID + "')\">删除</a>";

                            return strHtml;
                        }
                    }
                ];

                //组装自定义的列信息
                var customizeCols = $.array.map(result, function (item) {
                    if (defaultRow && !defaultRow[item.dbColName]) {
                        defaultRow[item.dbColName] = item.defaultValue ? item.defaultValue : "";
                    }
                    var col = {
                        field: item.dbColName,
                        title: item.title,
                        width: item.editViewW,
                        gatherable: item.colDataType == "gather" ? true : false,
                        sortable: item.Sortable != undefined ? item.Sortable : false,
                        hidable: item.Hidable != undefined ? item.Hidable : true
                    };

                    if (item.colInput && editors[item.colInput]) {
                        //设置编辑器类型
                        var editorObj = {
                            type: item.colInput
                        };
                        //设置编辑器参数
                        var editorOpts = {
                            required: item.mustFill
                        };
                        //处理下拉框编辑器
                        if (item.colInput == "combobox") {
                            editorOpts.url = columnComboboxUrl + item.spareCol2;
                            //给defaultRow的combobox列增加一个“用于显示text的临时属性”
                            //并设置formmater 指向该临时属性
                            var tempFieldForComboboxValue = item.dbColName + "_DicName";
                            if (defaultRow && !defaultRow[tempFieldForComboboxValue]) {
                                defaultRow[tempFieldForComboboxValue] = "";
                                col.formatter = function (val, theRow) {
                                    if (theRow[tempFieldForComboboxValue]) {
                                        return theRow[tempFieldForComboboxValue];
                                    }
                                    else { return theRow[item.dbColName]; }
                                }
                            }
                            if (item.multiple == true) {
                                editorOpts.multiple = true;
                            }
                        }

                        editorObj.options = editorOpts;
                        col.editor = editorObj;
                    }

                    return col;
                });
                var tempCols = [];
                if (showDefaultCols) {
                    tempCols = $.array.merge(defaults, customizeCols);
                }
                else {
                    if (customizeCols.length) { tempCols = customizeCols; }
                    else { tempCols = defaults; }
                }
                if (showOperateCols) {
                    $.array.merge(tempCols, operates);
                }
                cols.push(tempCols);
                if ($.isFunction(dgInit)) {
                    dgInit.call(this, cols);
                }

            });

        };

        var datagridInit = function (columns) {

            if (!columns || !$.isArray(columns)) { $.messager.alert("错误提醒", "列数据必须存在！"); return; }

            var options = {
                idField: "ID",
                rownumbers: true,
                fitColumns: false,
                remoteSort: false,
                fit: true,
                border: false,
                singleSelect: true,
                columns: columns,
                onBeginEdit: function (index, row) {
                    row.isEditing = true;
                },
                onEndEdit: function (index, row, changes) {
                    //此处获取 combobox 编辑器，用text对row的临时属性进行赋值
                    $.each(targetDg.datagrid("getEditors", index), function (i, editor) {
                        if (editor.type == "combobox") {
                            var opts = $(editor.target).combobox('options'), isMultiple = opts.multiple;
                            if (isMultiple) {
                                var vals = $(editor.target).combobox('getValues');
                                if (vals.length) {
                                    var ad = $(editor.target).combobox('getData'), valueField = opts.valueField, textField = opts.textField;
                                    var texts = $.array.filter(ad, function (d) {
                                        return $.array.contains(vals, d[valueField]);
                                    }).map(function (d) {
                                        return d[textField];
                                    });
                                    row[editor.field + '_DicName'] = texts.join(",");
                                }
                                else { row[editor.field + '_DicName'] = ""; }
                            } else {
                                var text = $(editor.target).combobox('getText');
                                row[editor.field + '_DicName'] = text;
                            }
                        }
                    });
                    row.isEditing = false;
                },
                toolbar: [
                    {
                        text: "新增", iconCls: "icon-add", handler: function () {
                            var targetIndex = getInsertRowIndex(), targetRow = $.extend({ ID: $.util.guid() }, defaultRow, { isEditing: true });
                            targetDg.datagrid("insertRow", { index: targetIndex, row: targetRow });
                            targetDg.datagrid("beginEdit", targetIndex);
                        }
                    }
                ],
                enableHeaderContextMenu: true,
                enableHeaderClickMenu: true,
                headerContextMenu: [
                    {
                        text: "用该字段汇总", iconCls: "icon-save",
                        disabled: function (e, menuItem, menu, target, field) {
                            var t = $(target),
                                copts = t.datagrid("getColumnOption", field);

                            return !copts.gatherable;
                        },
                        hideOnClick: true, bold: true,
                        handler: function (eventData, item, menu, grid, field) {
                            //console.log("右键事件对象：");
                            //console.log(eventData);

                            //console.log("当前点击的菜单项对象：");
                            //console.log(item);

                            //console.log("菜单对象：");
                            //console.log(menu);

                            //console.log("datagrid对象：");
                            //console.log(grid);

                            //console.log("正在点击的列：");
                            //console.log(field);

                            //记录
                            var cont = $("#groupedFieldInfo"), colOpts = targetDg.datagrid("getColumnOption", field);
                            var btn = $("<a />").linkbutton({
                                text: colOpts.title, onClick: function () {
                                    targetDg.datagrid("showColumn", field);
                                    btn.remove();
                                }
                            }).appendTo(cont);

                            //隐藏该列
                            targetDg.datagrid("hideColumn", field);

                            //发送查询数据请求
                            //targetDg.datagrid("load", { gatherField: field });
                            $.messager.alert("操作提醒", "应该发送查询数据请求");
                        }
                    }
                ],
                url: "/Demo/GetDatagridEditData3",
                queryParams: {},
                rowStyler: function (rowIndex, rowData) {
                    if (rowIndex < 2) {
                        return 'background-color:#6293BB;';
                    }
                }
            };

            targetDg.datagrid(options);
        };


        getColumns(datagridInit);
    });
</script>
